package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.MyBaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;
    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     *  最新订单和历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        log.info("page：{}, pageSize：{}", page, pageSize);
        //构造分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);
        //按下单日志排序
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("order_time");  //按下单时间降序排列
        //查询当前登陆用户的订单
        queryWrapper.eq("user_id", MyBaseContext.getCurrentId());
        orderService.page(pageInfo,queryWrapper);

        //查询订单明细
        pageInfo.getRecords().stream().map(item -> {
            List<OrderDetail> details =
                    orderDetailService.list(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getOrderId, item.getId()));
            item.setOrderDetails(details);
            return item;
        }).collect(Collectors.toList());
        return R.success(pageInfo);
    }

    //-------------------------------后台相关订单功能实现

    /**
     * 订单分页列表
     * @param page
     * @param pageSize
     * @param orderDto
     * @return
     */
    @GetMapping("/page")
    public R<Page> orderPages(int page, int pageSize, OrderDto orderDto) {
        log.info("page：{}, pageSize：{}", page, pageSize);
        //构造分页构造器
        Page<Orders> pageInfo = new Page(page, pageSize);
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(orderDto.getNumber()!=null, "number", orderDto.getNumber());
        queryWrapper.gt(orderDto.getBeginTime()!=null, "order_time", orderDto.getBeginTime());
        queryWrapper.lt(orderDto.getEndTime()!=null,"order_time",orderDto.getEndTime() );
        orderService.page(pageInfo, queryWrapper);
        //查询每个订单的下单人名称设置到订单中返回
        List<Orders> orders = pageInfo.getRecords();
        List<Orders> newOrders = new ArrayList<>();
        for (Orders order : orders) {
            Long userId = order.getUserId();
            User user = userService.getById(userId);
            //替换成了下单人
            order.setUserName(user.getName());
            newOrders.add(order);
        }
        pageInfo.setRecords(newOrders);
        return R.success(pageInfo);
    }

    /**
     * 订单分派：状态修改
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> modify(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.updateById(orders);
        return R.success("操作成功");
    }
}
